Repository navigation
Fix stale aligned field merge in PriorityMergeReader look-ahead - #19399
JackieTien97 merged 8 commits into
Conversation
There was a problem hiding this comment.
🟢 Approval recommended
No active review issues were identified for the changes preserving field priority when merging partial aligned rows.
No open issues 🎉
What changed in this PR
Fixes #19392 by preserving field priority when merging partial aligned rows, preventing stale values and incorrectly filtered results in ascending and descending scans.
Changes:
- Defers look-ahead skipping for incomplete aligned rows while retaining the optimization for complete rows.
- Preserves scalar points at
Long.MAX_VALUE, short-circuits completed field merges, and consolidates reader cleanup. - Adds unit and SQL regression coverage for priority ordering, partial updates, scan direction, and flush boundaries.
| File | Description |
|---|---|
iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/common/PriorityMergeReaderTest.java |
Tests maximum timestamps and strengthens row-count assertions. |
iotdb-core/datanode/src/test/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/common/AlignedPriorityMergeReaderTest.java |
Tests partial-row priority merging and complete-row skipping. |
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/common/PriorityMergeReader.java |
Guards look-ahead skipping and consolidates reader cleanup. |
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/common/AlignedPriorityMergeReader.java |
Checks row completeness and reports when field merging is complete. |
iotdb-core/datanode/src/main/java/org/apache/iotdb/db/storageengine/dataregion/read/reader/common/AlignedDescPriorityMergeReader.java |
Applies the same completeness checks to descending scans. |
integration-test/src/test/java/org/apache/iotdb/relational/it/query/old/aligned/IoTDBAlignedSeriesQueryTableIT.java |
Verifies SQL results and filters across partial updates and flushes. |
Review effort: Balanced
| static boolean hasNoNullFields(TimeValuePair pair) { | ||
| TsPrimitiveType value = pair.getValue(); | ||
| if (value == null) { | ||
| return false; | ||
| } | ||
| for (TsPrimitiveType field : value.getVector()) { | ||
| if (field == null || field.getValue() == null) { | ||
| return false; | ||
| } | ||
| } | ||
| return true; | ||
| } |
There was a problem hiding this comment.
I have a performance concern here for wide rows. If only the last field is null, hasNoNullFields() scans the entire vector just to determine that the lower-priority point must stay in the heap. fillNullValueInAligned() then scans the row again when the points are merged. In an in-memory microbenchmark with 256 fields and two readers whose timestamps fully overlapped, this case took about 210 ns per output row, compared with 130 ns with look-ahead skipping disabled. Could we track whether the row is complete while building the vector and check that flag here? That would preserve the fast path for complete rows while avoiding the extra scan.
There was a problem hiding this comment.
Makes total sense, thanks for benchmarking that! I removed hasNoNullFields() in 304bf2c and instead tracked completeness while building each row via a small AlignedPointReader interface across the TsBlock and AlignedTVList iterators (since TsVector is in tsfile). PriorityMergeReader now just checks that cached boolean in O(1), and all unit tests + the table IT pass locally. Ready for another look whenever you get a chance!
|
Could we give |
Good catch, I hadn't noticed table0 keeps its last batch in memory! Updated partialUpdateMergeAcrossMultipleFlushesTest in 0e55257 to create its own merge_lookahead_db database, flush with FLUSH merge_lookahead_db, and drop it in finally. Re-ran the IT locally and it passes. |
JackieTien97
left a comment
There was a problem hiding this comment.
Thanks for the fix and the follow-up to track row completeness while building vectors! The core correctness fix and aligned wide-row performance look solid, and the isolated table IT is clean.
Requesting changes mainly to avoid a 10%–17% performance regression on the non-aligned (scalar) PriorityMergeReader hot path (measured locally on JDK 21 with polymorphic call sites) and to add a small null-guard for topNext — see inline comments below.
|
|
||
| public void next() throws IOException { | ||
| timeValuePair = reader.nextTimeValuePair(); | ||
| currentRowComplete = isReaderRowComplete(reader); |
There was a problem hiding this comment.
reader is final, so calling isReaderRowComplete(reader) (which performs reader instanceof AlignedPointReader) inside Element.next() adds per-point overhead on every advance—including for non-aligned (scalar) PriorityMergeReader / DescPriorityMergeReader (which never read currentRowComplete), and for skipped lower-priority elements in updateHeap().
Also note setTimeValuePair() does not update currentRowComplete, which could leave it stale if ever called with a different pair.
Could we resolve AlignedPointReader once in the constructor and query it lazily in isCurrentRowComplete(), leaving Element.next() untouched?
private final AlignedPointReader alignedReader;
public Element(IPointReader reader, TimeValuePair timeValuePair, MergeReaderPriority priority) {
this.reader = reader;
this.alignedReader = reader instanceof AlignedPointReader ? (AlignedPointReader) reader : null;
this.timeValuePair = timeValuePair;
this.priority = priority;
}
public boolean isCurrentRowComplete() {
return alignedReader != null && alignedReader.isLastRowComplete();
}
public void next() throws IOException {
timeValuePair = reader.nextTimeValuePair();
}In PriorityMergeReader, the last call on an element's reader before isRowComplete(top) is always nextTimeValuePair(), and hasNextTimeValuePair() does not mutate isLastRowComplete() by contract, so querying alignedReader.isLastRowComplete() on demand is equivalent while incurring zero overhead in next().
There was a problem hiding this comment.
Thanks a lot for the detailed review and benchmarks! Addressed all four points in 9f21baf:
Resolved alignedReader once in Element's constructor and queried isLastRowComplete() lazily, leaving Element.next() untouched.
Added the hasOverlap fast path and topNext != null guard in PriorityMergeReader (plus a unit test for a null second nextTimeValuePair()).
Short-circuited the TsBinary check with if (complete && ...) in TsBlockAlignedRowPointReader, AlignedTVListIterator, and MultiAlignedTVListIterator.
Added direct unit tests for isLastRowComplete() across AlignedTVListIterator, OrderedMultiAlignedTVListIterator, and MergeSortMultiAlignedTVListIterator (complete rows, null TEXT values, deleted columns, and ensuring hasNextTimeValuePair() doesn't mutate it).
| Element top = heap.poll(); | ||
| TimeValuePair ret = top.getTimeValuePair(); | ||
| boolean retComplete = isRowComplete(top); | ||
| TimeValuePair topNext = null; | ||
| boolean canSkipNext = false; | ||
| if (top.hasNext()) { | ||
| top.next(); | ||
| topNext = top.currPair(); | ||
| canSkipNext = isRowComplete(top); | ||
| } | ||
| updateHeap(ret, topNext); | ||
| updateHeap(ret, topNext, retComplete, canSkipNext); |
There was a problem hiding this comment.
Two points here:
- Scalar / non-overlapping hot-path regression:
isRowComplete(top)is currently invoked twice via polymorphic dispatch on every output row even when there is no same-timestamp overlap (heap.isEmpty() || heap.peek().currTime() != ret.getTimestamp()). Combined withElement.next()doinginstanceof AlignedPointReaderper point, local microbenchmarks (JDK 21, 16k rows, megamorphicIPointReader/PriorityMergeReadercall sites) show a reproducible 10%–17% regression on non-aligned scalar scans (100% overlap: ~39 -> ~44 ns/row; interleaved non-overlap: ~23.1 -> ~25.5 ns/row; 1-reader drain: ~19.3 -> ~22.5 ns/row). - Null safety for
topNext: Iftop.hasNext()returnstrueand anIPointReaderreturnsnullfromnextTimeValuePair(),canSkipNext = isRowComplete(top)evaluates totruefor scalarPriorityMergeReader, causingtopNext.getTimestamp()inupdateHeapto throw an NPE (whereas both the previous code and line 101if (topNext != null)guard againsttopNext == null).
Both can be addressed cleanly by checking hasOverlap first and guarding topNext != null:
Element top = heap.poll();
TimeValuePair ret = top.getTimeValuePair();
boolean hasOverlap = !heap.isEmpty() && heap.peek().currTime() == ret.getTimestamp();
boolean retComplete = hasOverlap && isRowComplete(top);
TimeValuePair topNext = null;
boolean canSkipNext = false;
if (top.hasNext()) {
top.next();
topNext = top.currPair();
if (hasOverlap && topNext != null) {
canSkipNext = isRowComplete(top);
}
}
if (hasOverlap) {
updateHeap(ret, topNext, retComplete, canSkipNext);
}Together with caching alignedReader in Element, this completely eliminates the scalar regression in the benchmark while keeping all aligned gains.
| } else { | ||
| TsPrimitiveType val = col.getTsPrimitiveType(rowIndex); | ||
| vector[i] = val; | ||
| if (val == null || (val instanceof TsBinary && val.getBinary() == null)) { |
There was a problem hiding this comment.
Minor nit: guarding with if (complete && (val == null || (val instanceof TsBinary && val.getBinary() == null))) (same in AlignedTVListIterator and MultiAlignedTVListIterator) avoids repeating the instanceof TsBinary check for the remaining columns once a row already has a null slot.
|
|
||
| @Test | ||
| public void testSkipOlderReaderOnlyWhenNextAlignedRowIsComplete() throws IOException { | ||
| assertFalse( |
There was a problem hiding this comment.
Could we also add direct unit tests covering isLastRowComplete() on AlignedTVListIterator and MultiAlignedTVListIterator (OrderedMultiAlignedTVListIterator and MergeSortMultiAlignedTVListIterator) for complete vs. incomplete rows (including null TsBinary / deleted column cases)? Right now unit tests only exercise TsBlockAlignedRowPointReader and the non-AlignedPointReader fallback directly.
|
1. Row completeness in TsFile’s Consider exposing whether the last row returned by 2. Consistent reads across external TsFiles (non-blocking) I suggest tracking file precedence for The follow-up should define file precedence for both explicit file lists and directory inputs. Regression tests should verify that selecting additional columns or switching between a point lookup and a range scan preserves the value of the same field at the same timestamp. |
|
plz cp to dev/1.3 branch @samyak-jain-dev |
Done! Opened #19440 for dev/1.3 (adapted the IT to Tree model since dev/1.3 doesn't have the table model. |
Fixes #19392
Description
Root Cause
In
PriorityMergeReader.updateHeap(TimeValuePair ret, TimeValuePair topNext), when advancing a lower-priority readerethat sharedtopTime, the look-ahead optimization checkede.currTime() == topNextTimeand immediately calledfillNullValue(topNext, e.getTimeValuePair())before skippinge.For aligned time series (
AlignedPriorityMergeReaderandAlignedDescPriorityMergeReader),topNextcan containnullfield slots that must be filled in strict descending priority order across all readers present attopNextTime. Eagerly merging an older readereintotopNextwhile processingtopTimepopulatesnullfields with stale values before an intermediate-priority reader starting (or ending, for descending scans) attopNextTimeis visited. BecauseAlignedPriorityMergeReader.fillNullValueInAligned()only fillsnullslots, the fresher middle-priority field value is silently discarded.Trigger Scenario (Before vs. After)
With three separate aligned sources for device
d1(fieldsx,y):(10: null, 100),(20: null, 200)(20: null, 220)(10: 110, null),(20: 120, null)time = 20(20, 120, 220)(20, 120, 220)ORDER BY time)(10, 110, 100),(20, 120, 200)(staley)(10, 110, 100),(20, 120, 220)WHERE x = 120 AND y = 2200 rows(matching row filtered out)(20, 120, 220)The same bug symmetrically affects descending aligned scans (
AlignedDescPriorityMergeReader) when processingt=20and looking ahead tot=10.Fix
AlignedPointReader(extendingIPointReader) withboolean isLastRowComplete()so aligned row builders record row completeness while constructing eachTsVector— avoiding any extra vector scan on wide rows:TsBlockAlignedRowPointReaderand wired it intoAlignedSeriesScanUtil.getPointReader(TsBlock)andAlignedReadOnlyMemChunk.getPointReader().AlignedPointReaderinAlignedTVList.AlignedTVListIteratorandMultiAlignedTVListIteratorto track completeness while assembling each vector innextTimeValuePair().currentRowCompleteonElementwhenevernextTimeValuePair()is fetched (falling back conservatively tofalsefor non-AlignedPointReaderimplementations with zero vector scanning).PriorityMergeReader,AlignedPriorityMergeReader, andAlignedDescPriorityMergeReader:fillNullValue(topNext, ...)call from the look-ahead path.isRowComplete(Element)hook (alwaystruefor scalar readers;element.isCurrentRowComplete()for aligned readers):topNextis complete, the fast look-ahead skip optimization is preserved in O(1).topNextis incomplete (or comes from a non-trackingIPointReader), lower-priority readers stay in the heap with zero extra scan and merge in strict descending priority order whentopNextis popped.topNext == null,canSkipNextisfalse, so scalar points atLong.MAX_VALUEare never skipped.retis already complete (either fromisRowComplete(top)or oncefillNullValuereturnstrue),updateHeapshort-circuits remaining column scans across overlapping readers.releaseAndCloseElement(Element).Verification
AlignedPriorityMergeReaderTest:testAscScanMergesMiddlePriorityReaderAtNextTimestamp(reproduces [Bug] Table model: ascending scan returns a stale field value and a matching row is filtered out #19392)testDescScanMergesMiddlePriorityReaderAtNextTimestamp(symmetric descending aligned scan case)testAscScanPreservesOlderColumnsWhileMiddleOverridesOverlappingColumn(verifies 3-column partial merges across 3 priorities)testSkipOlderReaderOnlyWhenNextAlignedRowIsComplete(verifiesTsBlockAlignedRowPointReaderO(1) complete-row early skip in both asc/desc scans, incomplete-row retention,fillNullValueInAlignedcompletion reporting, and conservative no-scan fallback for non-AlignedPointReadersources)PriorityMergeReaderTest:testPointAtLongMaxValueNotSkippedWhenTopEnds(verifies points atLong.MAX_VALUEare preserved when a higher-priority reader ends)testAscandtestDescIoTDBAlignedSeriesQueryTableIT#partialUpdateMergeAcrossMultipleFlushesTest:ORDER BY time,ORDER BY time DESC, andWHERE x = 120 AND y = 220) both before and after flushing the 3rd batch, plus the symmetric descending-scan case../mvnw spotless:apply -pl iotdb-core/datanodeand./mvnw spotless:apply -pl integration-test -P with-integration-tests(passed)./mvnw test -pl iotdb-core/datanode -am -Dtest="AlignedPriorityMergeReaderTest,PriorityMergeReaderTest,*AlignedTVList*Test,*SeriesScan*Test" -Dsurefire.failIfNoSpecifiedTests=false(134/134 datanode tests passed)./mvnw test-compile -pl iotdb-core/datanode -am -P with-zh-locale -DskipTests(passed)python3 .github/scripts/check-it-selection.py(passed)./mvnw verify -DskipUTs -Dit.test=IoTDBAlignedSeriesQueryTableIT#partialUpdateMergeAcrossMultipleFlushesTest -DfailIfNoTests=false -Dfailsafe.failIfNoSpecifiedTests=false -pl integration-test -am -P TableSimpleIT -P with-integration-tests(1/1 passed inTableSimpleIT/ 1C1D; Apache RAT 0 unapproved; 1C3D runs in CI)